package com.h3c.nem.utils;

import com.eos.common.constant.StatusCodeEnum;
import com.eos.common.custom.BusinessException;
import com.h3c.sso.entity.RequestTicket;
import com.h3c.sso.util.Base64Util;
import com.h3c.sso.util.CryptUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class SsoTicketDec {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");


    public static String deSsoTicket(String str, String key) throws Exception {

        String[] strs = str.split("\\$");
        if (3 > strs.length) {
            throw new BusinessException(false, 202021, "SSO Ticket 格式错误");
        } else {
            String strSecurityIdentity = strs[0];
            String strExpireTime = strs[1];
            String strCookieExpireTime = strs[3];
            Calendar ca = Calendar.getInstance();
            ca.setTime(deserializeTime(strExpireTime, key));
            ca.add(Calendar.DATE, 1);// num为增加的天数，可以改变的
            Date d = ca.getTime();
            if (d.before(new Date())) {
                throw new BusinessException(StatusCodeEnum.TOKEN_FAIL);
            } else {
                byte[] source = getDeserializeBytes(strSecurityIdentity, key);
                String strIdentity = new String(source, "UTF-16LE");
                return strIdentity;
            }
        }

    }

    private static byte[] getDeserializeBytes(String str, String key) throws Exception {
        byte[] bytes = Base64Util.fromBase64String(str);
        return CryptUtil.desDecrypt(bytes, key);
    }


    private static Date deserializeTime(String timeStr, String key) throws Exception {
        byte[] bytes = Base64Util.fromBase64String(timeStr);
        String strTime = new String(bytes, "UTF-16LE");

        try {
            return sdf.parse(strTime);
        } catch (ParseException var6) {
            return sdf2.parse(strTime);
        }
    }

    private static Date deserializeExpireTime(String cookieExpireTimeStr, String key) throws Exception {
        return deserializeTime(cookieExpireTimeStr, key);
    }

    public static String requestTicket(String url, String key) throws Exception {
        RequestTicket ticket = RequestTicket.getInstance();
        ticket.setSiteId("aaa");
        ticket.setReturnUrl(url);
        return ticket.serialize(key);
    }


}
